﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace VistarFlashEditorV1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        string filename;
        string path = "";
        string filename2;
        string path2 = "";
        string newMacEntry = "";
        int errorCount;

        private void Form1_Load(object sender, EventArgs e)
        {
            entryBySerialRadioButton.Checked = true;
            binOneTextBox.Enabled = false;
            binTwoTextBox.Enabled = false;
            currentMacEntryTextBox.Enabled = false;
            currentSerialNumberTextBox.Enabled = false;
            newSerialNumberTextBox.MaxLength = 10;
            newMacEntryTextBox.MaxLength = 8;
        }

        private void entryBySerialRadioButton_CheckedChanged(object sender, EventArgs e)
        {
            if (entryBySerialRadioButton.Checked == true)
            {
                newSerialNumberTextBox.Enabled = true;
                newMacEntryTextBox.Enabled = false;
            }
        }

        private void entryByMacRadioButton_CheckedChanged(object sender, EventArgs e)
        {
            if (entryByMacRadioButton.Checked == true)
            {
                newSerialNumberTextBox.Enabled = false;
                newMacEntryTextBox.Enabled = true;
            }
        }

        private void AboutToolStripMenuItem_Click(object sender, EventArgs e)
        {
            AboutBox1 ab = new AboutBox1();

            ab.ShowDialog();
        }

        private void loadBinOneButton_Click(object sender, EventArgs e)
        {
            OpenFileDialog ofd = new OpenFileDialog();
            ofd.Title = "Open file...";
            ofd.Filter = "BIN files (*.bin)|*.bin|All files (*.*)|*.*";
            ofd.Multiselect = false;

            if (ofd.ShowDialog() == DialogResult.OK)
            {
                binOneTextBox.Text = ofd.FileName;
                path = binOneTextBox.Text;
                filename = binOneTextBox.Text.Substring(binOneTextBox.Text.LastIndexOf('\\') + 1);

            }

        }

        private void loadBinTwoButton_Click(object sender, EventArgs e)
        {
            OpenFileDialog ofd = new OpenFileDialog();
            ofd.Title = "Open file...";
            ofd.Filter = "BIN files (*.bin)|*.bin|All files (*.*)|*.*";
            ofd.Multiselect = false;

            if (ofd.ShowDialog() == DialogResult.OK)
            {
                binTwoTextBox.Text = ofd.FileName;
                path2 = binTwoTextBox.Text;
                filename2 = binTwoTextBox.Text.Substring(binTwoTextBox.Text.LastIndexOf('\\') + 1);
                
            }

        }

        private void readFlashDataButton_Click(object sender, EventArgs e)
        {
            if (path != "" && path2 != "")
            {
                string binOneMac, binOneAndTwoMacString = "";
                FileStream fs1 = new FileStream(@path, FileMode.Open, FileAccess.Read);
                long offset1 = fs1.Seek(1032192, SeekOrigin.Begin);   // Seek to FC000 (1032192th) byte in the file

                binOneMac = "0";

                int x = 0;
                while (x <= 1)
                {
                    binOneMac = fs1.ReadByte().ToString("X");
                    //if length is single digit add a 0 ( 1 now is 01)
                    if (binOneMac.Length == 1)
                    {
                        binOneMac = "0" + binOneMac;
                    }

                    if (x > 0)
                    {
                        currentMacEntryTextBox.Text += " " + binOneMac;
                        binOneAndTwoMacString += " " + binOneMac;
                    }
                    else
                    {
                        currentMacEntryTextBox.Text = binOneMac;
                        binOneAndTwoMacString = binOneMac;
                    }

                    x++;
                }
                fs1.Close();

                string binTwoMac;
                FileStream fs2 = new FileStream(@path2, FileMode.Open, FileAccess.Read);
                long offset2 = fs2.Seek(1032192, SeekOrigin.Begin);   // Seek to FC000 (1032192th) byte in the file

                binTwoMac = "0";

                x = 0;
                while (x <= 1)
                {
                    binTwoMac = fs2.ReadByte().ToString("X");
                    //if length is single digit add a 0 ( 1 now is 01)
                    if (binTwoMac.Length == 1)
                    {
                        binTwoMac = "0" + binTwoMac;
                    }


                    currentMacEntryTextBox.Text += " " + binTwoMac;
                    binOneAndTwoMacString += " " + binTwoMac;
                    

                    x++;
                }
                fs2.Close();

                //newMacEntryTextBox.Text = binOneAndTwoMacString;
                //the mac entry is stored in reverse in the bin files
                   char[] boat = binOneAndTwoMacString.ToCharArray();
                   string binOneAndTwoMacFixedString = string.Empty;
                   //int i = boat.Length - 1;

                   //while (i >= 0)
                   //{
                       binOneAndTwoMacFixedString += boat[9].ToString();
                       binOneAndTwoMacFixedString += boat[10].ToString();
                       binOneAndTwoMacFixedString += boat[8].ToString();
                       binOneAndTwoMacFixedString += boat[6].ToString();
                       binOneAndTwoMacFixedString += boat[7].ToString();
                       binOneAndTwoMacFixedString += boat[5].ToString();
                       binOneAndTwoMacFixedString += boat[3].ToString();
                       binOneAndTwoMacFixedString += boat[4].ToString();
                       binOneAndTwoMacFixedString += boat[2].ToString();
                       binOneAndTwoMacFixedString += boat[0].ToString();
                       binOneAndTwoMacFixedString += boat[1].ToString();
                   //    i--;
                   //}
                   currentMacEntryTextBox.Text = binOneAndTwoMacFixedString;

                   string serialNumber;
                   int serialNumberInt;

                   serialNumber = binOneAndTwoMacFixedString.Replace(" ", "");
                   serialNumberInt = int.Parse(serialNumber, System.Globalization.NumberStyles.HexNumber);
                    //int decAgain = int.Parse(hexValue, System.Globalization.NumberStyles.HexNumber);
                   currentSerialNumberTextBox.Text = "0" + serialNumberInt.ToString();
            }
            else
            {
                MessageBox.Show("Please load the flash files.", "Flash Not Loaded.", MessageBoxButtons.OK, MessageBoxIcon.Error);
            
            }
        }

        private void OpenToolStripMenuItem_Click(object sender, EventArgs e)
        {
            loadBinOneButton_Click(sender, e);
        }

        private void OpenBin2ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            loadBinTwoButton_Click(sender, e);
        }

        private void readInfoToolStripMenuItem_Click(object sender, EventArgs e)
        {
            readFlashDataButton_Click(sender, e);
        }

        private void writeButton_Click(object sender, EventArgs e)
        {
            errorCount = 0;

            if (path != "" && path2 != "")
            {
                if (entryByMacRadioButton.Checked == true)
                {
                    if (newMacEntryTextBox.Text != "")
                    {
                        newMacEntry = newMacEntryTextBox.Text;
                        //mac is already in hex form, just need to get the contents and verify
                        newMacEntry = newMacEntry.Replace(" ", "");
                        if (newMacEntry.Length == 8)
                        {
                            writeBins();
                        }
                        else
                        {
                            MessageBox.Show("MAC Entry should be 8 digits. Ex.[1001EED4]", "Invalid.", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                    }
                    else
                    {
                        MessageBox.Show("MAC Entry should be 8 digits. Ex.[1001EED4]", "Invalid.", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
                if (entryBySerialRadioButton.Checked == true)
                {
                    string newHexSerialNumber;
                    int newDecSerialNumber;


                    try
                    {
                        if (newSerialNumberTextBox.Text != "")
                        {
                            newDecSerialNumber = int.Parse(newSerialNumberTextBox.Text);
                            //verify the serial length and convert to hex
                            newHexSerialNumber = newDecSerialNumber.ToString("X");
                            newMacEntry = newHexSerialNumber;

                            if (newMacEntry.Length == 8)
                            {
                                writeBins();
                            }
                            else
                            {
                                MessageBox.Show("Serial Number entry should be 10 digits. Ex.[0268562132]", "Invalid.", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            }

                        }
                        else
                        {
                            MessageBox.Show("Serial Number entry should be 10 digits. Ex.[0268562132]", "Invalid.", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }


                    }

                    catch
                    {
                        MessageBox.Show("Invalid Entry.", "Flash Not Written.", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        errorCount = 1;
                    }

                }
            

            }
            else
            {
                MessageBox.Show("Please load the flash files.", "Flash Not Loaded.", MessageBoxButtons.OK, MessageBoxIcon.Error);

            }
        }

        public void writeBins()
        {

            //int errorCount = 0;

            //setup arrays
            string[] nmes = new string[4];
            byte[] nmesb = new byte[4];
            int[] nmesd = new int[4];
            string[] nmes_final = new string[4];

            //move the hex numbers into the correct order
            nmes[0] = newMacEntry[6].ToString() + newMacEntry[7].ToString();
            nmes[1] = newMacEntry[4].ToString() + newMacEntry[5].ToString();
            nmes[2] = newMacEntry[2].ToString() + newMacEntry[3].ToString();
            nmes[3] = newMacEntry[0].ToString() + newMacEntry[1].ToString();

            //convert the chars to int32, then to string, then byte again
            int x = 0;
            try
            {
                while (x <= 3)
                {
                    nmesd[x] = int.Parse(nmes[x], System.Globalization.NumberStyles.HexNumber);
                    nmes_final[x] = nmesd[x].ToString();
                    nmesb[x] = byte.Parse(nmes_final[x]);
                    x++;
                }

                //write to the first bin
                FileStream fs3 = new FileStream(@path, FileMode.Open, FileAccess.Write);
                long offset3 = fs3.Seek(1032192, SeekOrigin.Begin);   // Seek to 1032192th byte in the file
                x = 0;
                while (x <= 1)
                {
                    fs3.WriteByte(nmesb[x]);
                    x++;
                }

                fs3.Close();

                //write to the second bin
                FileStream fs4 = new FileStream(@path2, FileMode.Open, FileAccess.Write);
                long offset4 = fs4.Seek(1032192, SeekOrigin.Begin);   // Seek to 1032192th byte in the file

                while (x >= 2 && x <= 3)
                {
                    fs4.WriteByte(nmesb[x]);
                    x++;
                }

                fs4.Close();
            }
            catch
            {
                MessageBox.Show("Invalid Entry.", "Flash Not Written.", MessageBoxButtons.OK, MessageBoxIcon.Error);
                errorCount = 1;
            }

            if (errorCount == 0)
            {
                MessageBox.Show("Flash Files Updated.", "Success.", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }
        }

        private void SaveToolStripMenuItem_Click(object sender, EventArgs e)
        {
            writeButton_Click(sender, e);
        }

        private void ExitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.Close();
        }
    }
}
